package com.lh.feign;

import feign.Client;
import feign.Request;
import feign.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: linghao
 * @since: 2022/10/26
 */
public class FeignClient implements Client {

    private final Client delegate;
    private List<FeignClientInterceptor> interceptors;

    public FeignClient(Client delegate, List<FeignClientInterceptor> interceptors) {
        this.delegate = delegate;
        this.interceptors = interceptors;
    }

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        Map<String,Object> attchment = new HashMap<>();
        this.beforeExecute(request,attchment);
        Response response = this.delegate.execute(request, options);
        response = this.afterExecute(request,attchment,response,(Throwable)null);
        return response;
    }

    private void beforeExecute(Request request, Map<String, Object> attchment) {
        for(FeignClientInterceptor interceptor : interceptors){
            interceptor.beforeExecute(request,attchment);
        }
    }

    private Response afterExecute(Request request, Map<String, Object> attchment, Response response, Throwable e) {
        for(FeignClientInterceptor interceptor : interceptors){
            interceptor.afterExecute(request,attchment,response,e);
        }
        return response;
    }
}
